<?php


namespace Packages\Captcha\Services;

use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;
use Illuminate\Support\Facades\Cache;

class CaptchaService
{
    protected string $redisKey;

    public function __construct()
    {
        $this->redisKey = config('rediskey')['serverImgCode'];
    }

    /**
     * 验证码验证逻辑
     *
     * @param $data[] number 随机数
     * @param $data[] verifyCode 验证码
     * @return array
     * @author gl
     */
    public function verifyCode($data)
    {
        // 默认验证码
        if ($data['verifyCode'] == '6666') {
            return ['status' => true, 'data' => $data];
        }

        // 获取缓存中的验证码
        $code = Cache::get($this->redisKey . $data['number']);

        //验证码是否存在
        if (!$code) {
            return ['status' => false, 'msg' => '验证码已过期'];
        }

        // 转换为小写
        $verifyCode = strtolower($data['verifyCode']); // 转换为小写

        // 验证码是否正确
        if ($code != $verifyCode) {
            return ['status' => false, 'msg' => '验证码错误'];
        }

        return ['status' => true, 'data' => $verifyCode];
    }

    /**
     * 生成验证码
     *
     * @param array $data[] number 随机数
     * @return string
     * @author gl
     * @throws \Exception
     */
    public function captcha(array $data)
    {
        // 生成验证码图片的Builder对象，配置相应属性
        $phrase = new PhraseBuilder;

        // 设置验证码位数
        $code = $phrase->build(4);

        // 生成验证码图片的Builder对象，配置相应属性
        $builder = new CaptchaBuilder($code, $phrase);

        // 设置背景颜色
        $builder->setBackgroundColor(220, 210, 230); // 淡紫色
        // $builder->setBackgroundColor(255, 255, 255); // 白色

        $builder->setMaxAngle(25);
        $builder->setMaxBehindLines(0);
        $builder->setMaxFrontLines(0);

        // 可以设置图片宽高及字体 width height font
        $builder->build(100, 40, null);

        // 获取验证码的内容
        $phrase = $builder->getPhrase();

        // 把内容存入redis
        Cache::put($this->redisKey . $data['number'], strtolower($phrase), 180);

        // 生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header("Content-Type:image/jpeg");

        // 输出图片
        $builder->output();
    }
}
